package com.huifaapp.mall.selectImage;

import android.os.Environment;
import android.text.TextUtils;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class RootFile {
	public static final String APP_FILE_PATH = "/jdyh/";
	private static final String CHCHE_FILE_PATH = "/cache/";
	private static final String FAV_FILE = "/FavFile/";

	private static final String XY_CHCHE_FILE = "/bdCache/";
	private static final String XY_EMOTICONS = "/emoticons/";

	private static File rootFilePath = null;
	private static RootFile mFile;

	private RootFile(){
		rootFilePath = Environment.getExternalStorageDirectory();
	}

	public static RootFile getFileObj(){
		if (mFile == null) {
			mFile = new RootFile();
		}
		return mFile;
	}

	/**
	 *  创建APP目录文件夹
	 * */
	public static File getRootFiles(){
		if (rootFilePath == null) {
			rootFilePath = Environment.getExternalStorageDirectory();
		}
		return getFiles(rootFilePath.getPath() + APP_FILE_PATH);
	}



	public static File getFavFiles(){
		return getFiles(getRootFiles() + FAV_FILE);
	}

	/**
	 * 创建\获取表情文件夹
	 * @return
	 */
	public static File getEmoticonsDir(){
		return getFiles(getRootFiles() + XY_EMOTICONS);
	}

	/**
	 * 创建相约缓存目录
	 * @return
	 */
	public static File getXyCacheFiles() {
		return getFiles(getRootFiles() + XY_CHCHE_FILE);
	}

	/**
	 *  创建缓存目录文件夹
	 * */
	public static File getCacheFiles(){
		return getFiles(getRootFiles() + CHCHE_FILE_PATH);
	}

	public static boolean isExit(String path){
		File file = new File(path);
		if (file.exists()) {
			return true;
		}
		return false;
	}


	/**
	 * 写文件
	 * @param fileName 文件名称
	 * @param data 缓存的数据
	 */
	public static void wirteCacheFiles(String fileName, String data){
		wirteCacheFiles(fileName, data, true);
	}

	public static void wirteCacheFiles(String fileName, String data, boolean isMd5){
		FileOutputStream fout = null;
		try{
			File file = new File(getXyCacheFiles() + "/" + (isMd5 ? md5(fileName + 0) : fileName));
			fout = new FileOutputStream(file);
			if (!file.exists()) {
				file.mkdirs();
			}
			byte [] bytes = data.getBytes();
			fout.write(bytes);
		} catch(Exception e){
			e.printStackTrace();
		} finally {
			if (fout != null) {
				try {
					fout.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 读取缓存文件
	 * @param fileName 文件名
	 * @return
	 */
	public static String readCacheFiles(String fileName) {
		try {
			File file = new File(getXyCacheFiles() + "/" + md5(fileName + 0));
			if (!file.exists()) {
				return "";
			}
			StringBuffer sb = new StringBuffer();
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line = "";
			while((line = br.readLine())!=null){
				sb.append(line);
			}
			String result = new String(sb);
			br.close();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String md5(String string) {
	    byte[] hash;
	    try {
	        hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
	    } catch (NoSuchAlgorithmException e) {
	        throw new RuntimeException("Huh, MD5 should be supported?", e);
	    } catch (UnsupportedEncodingException e) {
	        throw new RuntimeException("Huh, UTF-8 should be supported?", e);
	    }
	    StringBuilder hex = new StringBuilder(hash.length * 2);
	    for (byte b : hash) {
	        if ((b & 0xFF) < 0x10) hex.append("0");
	        hex.append(Integer.toHexString(b & 0xFF));
	    }
	    return hex.toString();
	}



	/**
	 * 创建文件夹或者文件
	 * @param path 文件名
	 * @return
	 */
	public static File getFiles(String path){
		 if (!checkSdCardState() || path.equals("")) {
			 return null;
		 }
		 File file = new File(path);
		 if (!file.exists()) {
			 file.mkdirs();
		 }
		 return file;
	}

	/*
	 *  获得SD卡根目录路径
	 * */
	public static String getRootFilePath(){
		if (!checkSdCardState()) {
			return "/";
		}
		return rootFilePath.getPath();
	}

	/*
	 *  检测SD卡状态
	 * */
	public static boolean checkSdCardState(){
		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}

	/**
	 * 获取文件夹大小
	 * @param file
	 * @return
	 */
	public long getFolderSize(File file){
		if (file == null) {
			file = getCacheFiles();
		}
       long size = 0;
       try {
           File[] fileList = file.listFiles();
           for (int i = 0; i < fileList.length; i++) {
               if (fileList[i].isDirectory()) {
                   size = size + getFolderSize(fileList[i]);

               } else {
                   size = size + fileList[i].length();
               }
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
       return size;
    }

	/**
     * 格式化单位
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size/1024;
        if(kiloByte < 1) {
            return size + "B";
        }

        double megaByte = kiloByte/1024;
        if(megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte/1024;
        if(gigaByte < 1) {
            BigDecimal result2  = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte/1024;
        if(teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }

    /**
     * 删除指定目录下文件及目录
     * @param filePath
     * @param deleteThisPath
     * @return
     */
    public void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {// 处理目录
                    File files[] = file.listFiles();
                    for (int i = 0; i < files.length; i++) {
                        deleteFolderFile(files[i].getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {// 如果是文件，删除
                        file.delete();
                    } else {// 目录
                   if (file.listFiles().length == 0) {// 目录下没有文件或者目录，删除
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

	public static void deleteFile(String filePath){
		File file = new File(filePath);
		if (file.exists()) {
			file.delete();
		}
	}

	public static void writeObject(Object object, String path){
		ObjectOutputStream fos = null;
		try {
			File file = new File(path);
			if (file.exists()) {
				file.mkdirs();
			}
			fos = new ObjectOutputStream(new FileOutputStream(file));
			fos.writeObject(object);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos!=null) {
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static Object readObject(String path){
		Object object = null;
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(new File(path)));
			object = ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (ois!=null) {
					ois.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return object;
	}
}
